package com.qf.business.goods.controller;

import com.qf.business.goods.service.GoodsFenleiGuigeService;
import com.qf.business.goods.service.GoodsFenleiService;
import com.qf.data.base.r.R;
import com.qf.data.base.r.Rs;
import com.qf.data.base.utils.QfBeanUtils;
import com.qf.data.goods.entity.GoodsFenlei;
import com.qf.data.goods.vo.input.FenleiInput;
import com.qf.data.goods.vo.output.FenleiNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
@RestController
@RequestMapping("/fenlei")
@Slf4j
public class FenleiController {

    @Autowired
    private GoodsFenleiService goodsFenleiService;

    @Autowired
    private GoodsFenleiGuigeService goodsFenleiGuigeService;

    /**
     * 新增分类
     * @return
     */
    @RequestMapping("/insert")
    public R insert(FenleiInput input){
        GoodsFenlei goodsFenlei = QfBeanUtils.beanCopy(input, GoodsFenlei.class);
        goodsFenleiService.save(goodsFenlei);
        return Rs.create(true);
    }

    /**
     * 查询所有分类
     * @return
     */
    @RequestMapping("/list")
    public R list(){
        //转换
        List<FenleiNode> nodes = new ArrayList<>();

        //准备一个map
        Map<Long, FenleiNode> nodeMap = new HashMap<>();
        List<GoodsFenlei> fenleis = goodsFenleiService.list();
        for (GoodsFenlei fenlei : fenleis) {
            FenleiNode node = fenlei2Node(fenlei);
            nodeMap.put(node.getId(), node);
            if (fenlei.getPid() == null) {
                //顶级分类
                nodes.add(node);
            } else {
                //非顶级分类
                //从map中获取上一级的Node节点
                FenleiNode parentNode = nodeMap.get(fenlei.getPid());
                parentNode.addNode(node);
            }
        }
        return Rs.create(nodes);
    }

    /**
     * 给指定的分类设置规格
     * @return
     */
    @RequestMapping("/setguige")
    public R setFenleiGuige(Long fenleiId, String guigeIdStr){
        log.info("[set fenlei guige] - 设置分类规格 - {} | {}", fenleiId, guigeIdStr);
        goodsFenleiGuigeService.updateFenleiGuige(fenleiId, guigeIdStr.split("-"));
        return Rs.create(true);
    }




    /**
     * 将分类对象 转换成 node节点对象
     * @return
     */
    private FenleiNode fenlei2Node(GoodsFenlei goodsFenlei){
        FenleiNode fenleiNode = new FenleiNode();
        fenleiNode.setId(goodsFenlei.getId());
        fenleiNode.setFenleiName(goodsFenlei.getFenleiName());
        return fenleiNode;
    }
}
